package net.bat.task;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import net.bat.util.Cfg;
import net.sk.pt.IConsumer;
import net.sk.pt.State;
import net.sk.pt.StateUtil;
import net.sk.ws.WSket;
/**
 * 长周期任务
 * @author chen4w
 * @version 1.0
 */
public class Task {
	private String sid=null;
	public String getSid() {
		return sid;
	}
	public void setSid(String sid) {
		this.sid = sid;
	}
	/**
	 * 完成情况
	 */
	private String info=null;
	private String title = null;
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
		sendTask(new String[]{"id","title"});
	}
	public String getInfo() {
		return info;
	}
	private void sendTask(String[] props){
		if(sid==null)
			return;
		HashMap<Object,WSket> wsMap = Cfg.getSC().getWSMap(sid);
		if(wsMap!=null){
			State s =StateUtil.obj2sta(this,props, State.ACTION_PUT);
			Iterator<Entry<Object, WSket>> iter = wsMap.entrySet().iterator(); 
			while (iter.hasNext()) { 
				Entry<Object, WSket> entry = iter.next(); 
				WSket cur = entry.getValue(); 
				cur.send(null, s);
			} 							
		}
	}
	public void setInfo(String taskInfo) {
		this.info = taskInfo;
		sendTask(new String[]{"id","info"});
	}
	/**
	 * 任务标识
	 */
	private String id;
	/**
	 * 任务总长度
	 */
	private long total=-1;
	/**
	 * 当前进度
	 */
	private long cur=-1;
	private float fcur;
	/**
	 * 最后一次更新进度时间
	 */
	private Date lastAccess = new Date();
	
	public Date getLastAccess() {
		return lastAccess;
	}
	public void setLastAccess(Date lastAccess) {
		this.lastAccess = lastAccess;
	}
	/**
	 * 
	 * @param val 任务标识
	 */
	public Task(String val,String sid){
		this.id=val;
		this.sid = sid;
	}
	public String getId(){
		return id;
	}
	public void setId(String val){
		this.id = val;
	}
	public long getTotal(){
		return this.total;
	}
	public void setTotal(long val){
		this.total=val;
		sendTask(new String[]{"id","total"});
	}
	public long getCur(){
		return this.cur;
	}
	public void setCur(long val){
		this.info = val+"/"+total;
		this.cur=val;
		this.fcur = val/(float)total;
		sendTask(new String[]{"id","fcur","info"});
	}
	public float getFcur() {
		return fcur;
	}
	public void setFcur(float fcur) {
		this.fcur = fcur;
	}
	public void done(){
		TaskCenter.done(this.sid);
		if(sid==null)
			return;
		HashMap<Object,WSket> wsMap = Cfg.getSC().getWSMap(sid);
		if(wsMap!=null){
			State s =StateUtil.obj2sta(this,new String[]{"id"}, State.ACTION_REMOVE);
			Iterator<Entry<Object, WSket>> iter = wsMap.entrySet().iterator(); 
			while (iter.hasNext()) { 
				Entry<Object, WSket> entry = iter.next(); 
				WSket cur = entry.getValue(); 
				cur.send(null, s);
			} 							
		}
	}
}
